package com.zhang.first.day05;

import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.watermark.Watermark;
import org.apache.flink.streaming.api.windowing.assigners.EventTimeSessionWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.sql.Timestamp;

/**
 * 自己发送水位线
 *
 * @title: 使用 实现会话窗口
 * @author: zhang
 * @date: 2022/1/18 13:13
 */
public class Example4 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .addSource(new SourceFunction<Integer>() {
                    @Override
                    public void run(SourceContext<Integer> ctx) throws Exception {
                        ctx.collectWithTimestamp(1, 1000L);
                        Thread.sleep(1000L);
                        ctx.collectWithTimestamp(1, 2000L);
                        ctx.collectWithTimestamp(1, 8000L);
                        ctx.collectWithTimestamp(1, 12000L);
                      //  Thread.sleep(1000L);
                        ctx.emitWatermark(new Watermark(50000000L));

                        //ctx.collectWithTimestamp(1, 3000L);
                    }

                    @Override
                    public void cancel() {

                    }
                })
                .keyBy(r -> 1)
                .window(EventTimeSessionWindows.withGap(Time.seconds(5)))
                .process(new ProcessWindowFunction<Integer, String, Integer, TimeWindow>() {
                    @Override
                    public void process(Integer integer, ProcessWindowFunction<Integer, String, Integer, TimeWindow>.Context context, Iterable<Integer> elements, Collector<String> out) throws Exception {
                        out.collect("窗口" + new Timestamp(context.window().getStart()) + "~~"
                                + new Timestamp(context.window().getEnd()) +
                                "共有" + elements.spliterator().getExactSizeIfKnown() + " 个元素");
                    }
                })
                .print();

        env.execute();
    }
}
